package com.jweb.framework.security.crypto.cipher.asymmetric;

import java.security.KeyStore;
import java.security.PublicKey;
import java.security.cert.Certificate;

import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;

/**
 * 修改人： Thomas
 * 修改内容：新增 
 * 类说明：JKS格式公钥工厂
 */
public class JksPublicKeyFactoryBean implements FactoryBean<PublicKey>, InitializingBean {
	
	protected KeyStore keyStore;
	protected String alias;
	protected PublicKey publicKey;
	
	public PublicKey getObject() throws Exception {
		return this.publicKey;
	}
	
	public Class<?> getObjectType(){
		return PublicKey.class;
	}
	
	public boolean isSingleton(){
		return true;
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		Certificate certificate = this.keyStore.getCertificate(this.alias);
		
		if(certificate == null){
			throw new AsymmetricEncryptionException("No such public key with alias: " + this.alias);
		}
		
		this.publicKey = certificate.getPublicKey();
	}
	
	public void setKeyStore(KeyStore keyStore){
		this.keyStore = keyStore;
	}
	
	public void setAlias(String alias){
		this.alias = alias;
	}
	
}
